from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse
from .. import models
from . import huiyuan_views,wupin_views

# 添加
def jiahuo(request):
    # 查询所有的分类  进行返回
    types = wupin_views.tab()
    return render(request,'myadmin/shangpin/shangjia.html',{'types':types})
# 添加数据
def chenggong(request):
     # 接受用户的信息

    ginfo = request.POST.dict()
    ginfo.pop('csrfmiddlewaretoken')
    file = request.FILES.get('g_url')
    if not file:
        return HttpResponse('<script>alert("请选择图片");history.back(-1)</script>')
    # 调图片上传
    g_url=huiyuan_views.touxiang(file)
    # 入库
    goods = models.Goods()
    goods.title=ginfo['title']
    goods.ordernum=ginfo['ordernum']
    goods.g_url=g_url
    goods.price=ginfo['price']
    goods.ginfo=ginfo['ginfo']
    goods.cateid=models.Shang.objects.get(id=ginfo['cateid'])
    goods.save()
    # 返回
    return render(request,'myadmin/shangpin/chakan.html')

def chakan(request):
    goods = models.Goods.objects.all()
    return render(request,'myadmin/shangpin/chakan.html',{'goods':goods})

def gaizheng(request):
    uid=request.GET.get('uid')
    if request.method=='GET':
        user = models.Goods.objects.get(id=uid)
        return render(request,'myadmin/shangpin/gaizheng.html',{'user':user})
    elif request.method=='POST':
        info = request.POST.dict()
        goods = models.Goods()
        goods.title = info['title']
        goods.ordernum = info['ordernum']
        goods.price = info['price']
        goods.ginfo = info['ginfo']
        goods.cateid = models.Shang.objects.get(id=info['cateid'])
        goods.save()
        return redirect(reverse('admin_liebiao'))

def shanle(request):
    uid=request.GET.get('uid')
    user = models.Goods.objects.get(id=uid)
    user.delete()
    return redirect(reverse('admin_chakan'))